<?php

namespace app\admin\controller;

use app\base\model\system\{SystemAdmin, SystemAdminLoginLog};
use app\core\exception\ErrorCode;
use app\core\util\{JwtUtil, TokenUtil, ToolUtil};
use think\Request;
use think\Session;

class AdminLoginController extends AdminBaseController
{
    /**
     * Desc: 管理员登录
     * Date: 2019/11/4 2:54
     * Author: yiyu
     * @param Request $request
     * @return \think\response\Json
     */
    public function Login(Request $request)
    {

        list($adminName, $adminPwd) = ToolUtil::postMore(['admin_name', 'admin_pwd'], $request, true);

        if (empty($adminName)) {
            return $this->errorReturn(ErrorCode::COMMON_LACK_PARAMS, '登录账号不能为空');
        }

        if (empty($adminPwd)) {
            return $this->errorReturn(ErrorCode::COMMON_LACK_PARAMS, '登录密码不能为空');
        }

        $error = Session::get(SystemAdmin::LOGIN_ERROR_SESSION_KEY) ? Session::get(SystemAdmin::LOGIN_ERROR_SESSION_KEY) : ['num' => 0, 'time' => time()];
        if (isset($error['num'], $error['time']) && $error['num'] >= 5 && $error['time'] > strtotime('- 5 minutes')) {
            return $this->errorReturn(ErrorCode::USER_LOGIN_MORE_ERROR);
        }

        //检验帐号密码
        try {
            $admin_id = SystemAdmin::login($adminName, $adminPwd);

            SystemAdminLoginLog::writeAdminLoginLog($admin_id);

            $token = JwtUtil::getToken(['admin_id' => $admin_id]);

            //设置一个token副本，用于校验注销
            TokenUtil::setAdminLoginTokenCopy($token);
            Session::delete(SystemAdmin::LOGIN_ERROR_SESSION_KEY);
            return $this->successReturn(['AUTHORIZATION' => $token]);
        } catch (\Exception $e) {
            $errorCode = $e->getCode();
            if (ErrorCode::USER_LOGIN_PASSWORD_ERROR === $errorCode) {
                $error['num'] += 1;
                $error['time'] = time();
                Session::set(SystemAdmin::LOGIN_ERROR_SESSION_KEY, $error);
            }

            return $this->errorReturn($errorCode, $e->getMessage());
        }


    }


    /**
     * Desc: 管理员注销
     * Date: 2019/10/19 22:41
     * Author: yiyu
     */
    public function Logout()
    {
        //删除token副本
        TokenUtil::delAdminLoginTokenCopy(TokenUtil::getRequestToken());
        return $this->successReturn();
    }


    /**
     * Desc: 生成验证码
     * Date: 2019/10/19 22:42
     * Author: yiyu
     * @return \think\Response
     */
    public function captcha()
    {
        ob_clean();
        $captcha = new \think\captcha\Captcha([
            'codeSet' => '0123456789',
            'length' => 4,
            'fontSize' => 30
        ]);
        return $captcha->entry();
    }

}